package com.stable.actor.network;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.nio.charset.StandardCharsets;


/**
 * 协议消息编解码器
 */
public class MessageCodec {


    public static byte[] encode(ProtocolMessage message) {
        try {
            // 启用WriteClassName特性以保留类型信息
            String json = JSON.toJSONString(message, SerializerFeature.WriteClassName);
            return json.getBytes(StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("消息编码失败: " + e.getMessage(), e);
        }
    }

    public static ProtocolMessage decode(byte[] data) {
        String jsonData ="";
        try {
         ParserConfig config = new ParserConfig();
         // Add common package patterns
         config.addAccept("com.datasophon.");
         config.addAccept("com.stable.");
         config.addAccept("com.alibaba.fastjson.");

         jsonData = new String(data, StandardCharsets.UTF_8);
         return JSON.parseObject(jsonData, ProtocolMessage.class, config);

        } catch (Exception e) {
            throw new RuntimeException("消息："+jsonData+",解码失败: " + e.getMessage(), e);
        }
    }
}
